﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Hardcodet.Wpf.TaskbarNotification;
using System.Diagnostics;
using System.Text;
using Guids;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Reflection;

namespace GuidGeneratorWPF
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		private static App current;
		private TaskbarIcon taskbarIcon;
		private HotKey hotKeyCopyGuid;
		private HotKey hotKeyCopyMultipleGuids;
		private HelpWindow helpWindow;
		private GuidGeneratorWindow mainWindow;

		public App()
		{
			current = this;
		}

		internal new static App Current { get { return current; } }

		public bool RegisteredCopyGuidHotKey { get; private set; }
		public bool RegisteredCopyMultipleGuidsHotKey { get; set; }

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			this.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;

			if (GuidGeneratorWPF.Properties.Settings.Default.SettingsNeedUpgraded)
			{
				GuidGeneratorWPF.Properties.Settings.Default.Upgrade();
				GuidGeneratorWPF.Properties.Settings.Default.SettingsNeedUpgraded = false;
			}

			taskbarIcon = (TaskbarIcon)FindResource("taskbarIcon");

			string warningMessage = null;

			hotKeyCopyGuid = new HotKey();
			hotKeyCopyGuid.HotKeyPressed += this.OnHotKeyCopyGuidPressed;
			try
			{
				hotKeyCopyGuid.RegisterGlobalHotKey(System.Windows.Forms.Keys.G, 8);
				this.RegisteredCopyGuidHotKey = true;
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
				warningMessage = "Failed to register 'Generate GUID' hotkey (Win-G).";
			}

			hotKeyCopyMultipleGuids = new HotKey();
			hotKeyCopyMultipleGuids.HotKeyPressed += this.OnHotKeyCopyMultipleGuidsPressed;
			try
			{
				hotKeyCopyMultipleGuids.RegisterGlobalHotKey(System.Windows.Forms.Keys.H, 8);
				this.RegisteredCopyMultipleGuidsHotKey = true;
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
				if (!string.IsNullOrEmpty(warningMessage))
					warningMessage += Environment.NewLine;

				warningMessage += "Failed to register 'Generate Multiple GUIDs' hotkey (Win-H).";
			}

			if (!string.IsNullOrEmpty(warningMessage))
				taskbarIcon.ShowBalloonTip("GUID Generator", warningMessage, BalloonIcon.Warning);
		}

		private void Application_Exit(object sender, ExitEventArgs e)
		{
			GuidGeneratorWPF.Properties.Settings.Default.Save();
		}

		private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			this.HandleException(e.Exception);
			e.Handled = true;
		}

		private void OnHotKeyCopyGuidPressed(object sender, EventArgs e)
		{
			App.GenerateGuid();
		}

		private void MenuItemOptions_Click(object sender, RoutedEventArgs e)
		{
			this.ShowOptionsWindow();
		}

		internal void ShowOptionsWindow()
		{
			if (mainWindow == null || !mainWindow.IsLoaded)
			{
				mainWindow = new GuidGeneratorWindow();
				mainWindow.Show();
			}
			else
			{
				mainWindow.Activate();
			}
		}

		private void MenuItemHelp_Click(object sender, RoutedEventArgs e)
		{
			this.ShowHelpWindow();
		}

		internal void ShowHelpWindow()
		{
			if (helpWindow == null || !helpWindow.IsLoaded)
			{
				helpWindow = new HelpWindow();
				helpWindow.Show();
			}
			else
			{
				helpWindow.Activate();
			}
		}

		private void OnHotKeyCopyMultipleGuidsPressed(object sender, EventArgs e)
		{
			App.GenerateMultipleGuids();
		}

		private void MenuItemExit_Click(object sender, RoutedEventArgs e)
		{
			this.Shutdown();
		}

		private void MenuItemGenerateMultipleGuids_Click(object sender, RoutedEventArgs e)
		{
			App.GenerateMultipleGuids();
		}

		private void MenuItemGenerateGuid_Click(object sender, RoutedEventArgs e)
		{
			App.GenerateGuid();
		}

		internal static string GenerateGuid()
		{
			var settings = GuidGeneratorWPF.Properties.Settings.Default;

			string guid = GuidGenerator.GenerateGuid(settings.GuidFormat, settings.UpperCase);

			Clipboard.SetText(guid);

			return guid;
		}

		internal static string GenerateMultipleGuids()
		{
			GuidCountWindow window = new GuidCountWindow();

			if (!window.ShowDialog() ?? false)
				return null;

			int count = 0;

			if (!int.TryParse(window.textBoxCount.Text, out count))
			{
				MessageBox.Show("Please enter a valid number.");
				GenerateMultipleGuids();
			}

			var settings = GuidGeneratorWPF.Properties.Settings.Default;

			GuidFormats guidFormat = settings.GuidFormat;
			bool upperCase = settings.UpperCase;

			string guids = GuidGenerator.GenerateMultipleGuids(count, guidFormat, upperCase);

			Clipboard.SetText(guids);

			return guids;
		}

		internal void HandleException(Exception ex)
		{
			Debug.WriteLine(ex);
			MessageBox.Show(ex.ToString(), "GUID Generator");
		}

		public bool StartWithWindows
		{
			get
			{
				RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", false);
				if (key != null)
				{
					object objectValue = RuntimeHelpers.GetObjectValue(key.GetValue("Guid Generator"));
					if (objectValue != null)
					{
						string executablePath = Assembly.GetExecutingAssembly().Location;

						if (string.Compare(objectValue.ToString(), executablePath, true) != 0)
						{
							Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true).SetValue("Guid Generator", executablePath);
						}
						return true;
					}
				}
				return false;
			}
			set
			{
				RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
				if (value)
				{
					key.SetValue("Guid Generator", Assembly.GetExecutingAssembly().Location);
				}
				else
				{
					key.DeleteValue("Guid Generator", false);
				}
			}
		}
	}
}
